<template>
  <div style="width: 100%;margin: 10px 0 0 0;">
        <el-row v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" key="meterAlarmQueryForm" :size="size" v-show="showSearch"
                     :label-width="labelWidth" >
              <div id="searchFilter" style="display: flex; justify-content: start; flex-wrap: wrap">
                <el-form-item label="处理状态" prop="handleStatus">
                  <el-select v-model="queryParams.handleStatus" placeholder="请选择处理状态" size="mini" style="width: 100%;" @change="handleQuery">
                    <el-option v-for="dict in dict.type.warn_handle_status" :key="dict.value" :label="dict.label"
                               :value="dict.value">{{ dict.label }}
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- 时间范围 -->
                <el-form-item label="报警时间" prop="recentlyWarnTime">
                  <el-date-picker size="mini" :clearable="false"
                    v-model="recentlyWarnTime"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%;"
                    @change="handleQuery">
                  </el-date-picker>
                </el-form-item>
                <el-form-item style="width: 0px">
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-tabs v-model="activeKey" size="mini" @tab-click="handleClick">
            <el-tab-pane v-for="item in AlarmType" :name="item.PTypeValue" :key="item.PTypeValue"
                         :label="item.PTypeName" class="ant-tabs">
              <el-table v-loading="loading" :data="warnList" border size="mini"
                        @selection-change="handleSelectionChange" :height="getAvailableHeight" style="margin-top: 10px;">
                <el-table-column type="index" label="#" width="40" align="center"/>
                <!-- <el-table-column label="平台主键" align="center" prop="id" :show-overflow-tooltip="true" />
                <el-table-column label="租户ID" align="center" prop="tenantId" :show-overflow-tooltip="true" /> -->
                <!--                <el-table-column label="报警对象类型" align="center" prop="targetType" width="120"-->
                <!--                                 :show-overflow-tooltip="true">-->
                <!--                  <template slot-scope="scope">-->
                <!--                    <dict-tag :options="dict.type.warntargettype" :value="scope.row.targetType"/>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
<!--                <el-table-column label="设备编号" align="center" prop="targetId" width="150"-->
<!--                                 :show-overflow-tooltip="true" sortable="custom"-->
<!--                                 :sort-orders="['ascending', 'descending']"/>-->
                <!--                <el-table-column label="报警对象名称" align="center" prop="targetName" width="150"-->
                <!--                                 :show-overflow-tooltip="true"/>-->
                <!-- ，0未确认，1已确认 -->
<!--                <el-table-column label="报警状态" align="center" prop="warnStatus" :show-overflow-tooltip="true"-->
<!--                                 sortable="custom" :sort-orders="['ascending', 'descending']" width="160">-->
<!--                  <template slot-scope="scope">-->
<!--                    <dict-tag :options="dict.type.warn_status" :value="scope.row.warnStatus"/>-->
<!--                  </template>-->
<!--                </el-table-column>-->
                <!-- ，0未处理，1已处理 -->
<!--                <el-table-column label="处理状态" align="center" prop="handleStatus" :show-overflow-tooltip="true"-->
<!--                                 sortable="custom" :sort-orders="['ascending', 'descending']" width="160">-->
<!--                  <template slot-scope="scope">-->
<!--                    <dict-tag :options="dict.type.warn_handle_status" :value="scope.row.handleStatus"/>-->
<!--                  </template>-->
<!--                </el-table-column>-->
                <el-table-column label="报警时间" align="center" prop="startTime" width="180"
                                 :show-overflow-tooltip="true" sortable="custom"
                                 :sort-orders="['ascending', 'descending']">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="报警类型" align="center" prop="warnParamType" :show-overflow-tooltip="true"
                                 width="140" sortable="custom" :sort-orders="['ascending', 'descending']">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_param_type" :value="scope.row.warnParamType"/>
                  </template>
                </el-table-column>
                <!-- ，1超上限，2超下限，3阈值，4累计，5连续 -->
                <!--                <el-table-column label="报警类型" align="center" prop="warnType" :show-overflow-tooltip="true">-->
                <!--                  &lt;!&ndash; <template slot-scope="scope">-->
                <!--                    <dict-tag :options="dict.type.warnparamtype" :value="scope.row.warnType"/>-->
                <!--                  </template> &ndash;&gt;-->
                <!--                </el-table-column>-->

                <!--                <el-table-column label="最近报警时间" align="center" prop="recentlyWarnTime" width="180"-->
                <!--                                 :show-overflow-tooltip="true">-->
                <!--                  <template slot-scope="scope">-->
                <!--                    <span>{{ parseTime(scope.row.recentlyWarnTime, '{y}-{m}-{d}') }}</span>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <!--                <el-table-column label="数据冻结时间" align="center" prop="freezeTime" width="180"-->
                <!--                                 :show-overflow-tooltip="true">-->
                <!--                  <template slot-scope="scope">-->
                <!--                    <span>{{ parseTime(scope.row.freezeTime, '{y}-{m}-{d}') }}</span>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <el-table-column label="报警值" align="center" prop="warnValue" :show-overflow-tooltip="true"
                                 width="180" sortable="custom" :sort-orders="['ascending', 'descending']"/>
                <el-table-column label="参考值" align="center" prop="referenceValue" :show-overflow-tooltip="true"
                                 sortable="custom" :sort-orders="['ascending', 'descending']"/>
                <el-table-column label="差值" align="center" prop="Value" :show-overflow-tooltip="true"
                                 sortable="custom" :sort-orders="['ascending', 'descending']"/>
                <!--                <el-table-column label="确认人" align="center" prop="confirmedBy" :show-overflow-tooltip="true"/>-->
                <!--                <el-table-column label="派单状态" align="center" prop="pd" :show-overflow-tooltip="true"/>-->
                <!--                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120"-->
                <!--                                 fixed="right">-->
                <!--                  <template slot-scope="scope">-->
                <!--                    <el-button-->
                <!--                        size="mini"-->
                <!--                        type="text"-->
                <!--                        icon="el-icon-edit"-->
                <!--                        @click="handleUpdate(scope.row)"-->
                <!--                        v-hasPermi="['alarmmanagement:warn:edit']"-->
                <!--                    >修改-->
                <!--                    </el-button>-->
                <!--                    <el-button-->
                <!--                        size="mini"-->
                <!--                        type="text"-->
                <!--                        icon="el-icon-delete"-->
                <!--                        @click="handleDelete(scope.row)"-->
                <!--                        v-hasPermi="['alarmmanagement:warn:remove']"-->
                <!--                    >删除-->
                <!--                    </el-button>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
              </el-table>

              <pagination
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
            </el-tab-pane>
          </el-tabs>
        </el-row>

    <!-- 添加或修改告警对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警对象类型" prop="targetType">
          <el-select v-model="form.targetType" placeholder="请选择报警对象类型">
            <el-option
              v-for="dict in dict.type.warntargettype"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警对象" prop="targetId">
          <el-input v-model="form.targetId" placeholder="请输入报警对象ID"/>
        </el-form-item>
        <el-form-item label="报警对象名称" prop="targetName">
          <el-input v-model="form.targetName" placeholder="请输入报警对象名称"/>
        </el-form-item>
        <el-form-item label="报警参数" prop="warnParamType">
          <el-select v-model="form.warnParamType" placeholder="请选择报警参数">
            <el-option
              v-for="dict in dict.type.warnparamtype"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最近报警时间" prop="recentlyWarnTime">
          <el-date-picker clearable
                          v-model="form.recentlyWarnTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择最近报警时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数据冻结时间" prop="freezeTime">
          <el-date-picker clearable
                          v-model="form.freezeTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择数据冻结时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报警值-实际数值" prop="warnValue">
          <el-input v-model="form.warnValue" placeholder="请输入报警值-实际数值"/>
        </el-form-item>
        <el-form-item label="参考值" prop="referenceValue">
          <el-input v-model="form.referenceValue" placeholder="请输入参考值"/>
        </el-form-item>
        <el-form-item label="差值" prop="Value">
          <el-input v-model="form.Value" placeholder="请输入差值"/>
        </el-form-item>
        <el-form-item label="确认人" prop="confirmedBy">
          <el-input v-model="form.confirmedBy" placeholder="请输入确认人"/>
        </el-form-item>
        <el-form-item label="派单状态" prop="pd">
          <el-input v-model="form.pd" placeholder="请输入派单状态"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDicts } from '@/api/system/dict/data.js'
import moment from 'moment'
import {listxbWarn, getWarn, delWarn, addWarn, updateWarn} from "@/api/alarm/alarmall";
import {listMeterSheetsTree} from "@/api/basedata/meterSheets";

export default {
  name: "MeteredWarn",
  dicts: ['warnparamtype', 'warntargettype', 'warn_handle_status', 'warn_status', 'warn_param_type', 'belong_department'],
  data() {
    return {
      screenHeight: null,
      // 按钮状态
      buttonAll: false,
      buttonStress: true,
      buttonAccumulative: true,
      buttonData: true,
      buttonCommunication: true,
      buttonEmpty: true,
      buttonVoltmetre: true,
      buttonDays: true,
      buttonMagnet: true,
      buttonInstant: true,
      size: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: '3',
      labelWidth: '80px',
      // 报警时间区间
      recentlyWarnTime: [moment().subtract(6, 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      defaultProps: {
        children: "children",
        label: "name"
      },
      AreaName: '',
      // 区域树选项
      sheetsTreeList: [],
      // 区域名称
      keyWordName: undefined,
      // 遮罩层
      loading: true,
      treeLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警表格数据
      warnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        id: null,
        sheetsCode: null,
        tenantId: null,
        targetType: 2,
        targetId: null,
        targetName: null,
        warnStatus: null,
        handleStatus: null,
        warnParamType: null,
        warnType: null,
        beginStartTime: null,
        endStartTime: null,
        freezeTime: null,
        warnValue: null,
        referenceValue: null,
        Value: null,
        confirmedBy: null,
        pd: null,
        terminalType: 1,
      },
      // tabs
      activeKey: '',
      AlarmType: [
        // {PTypeValue: '', PTypeName: '全部类型'},
        // {PTypeValue: 'zeroUsage', PTypeName: '持续零用量'},
        // {PTypeValue: 'missUpload', PTypeName: '持续未上报'},
        // {PTypeValue: 'flowIncrease', PTypeName: '用量突增'},
        // { PTypeValue:'handleData',PTypeName:'数据不完整'},
        // { PTypeValue:'handleCommunication',PTypeName:'通讯故障'},
        // { PTypeValue:'handleEmpty',PTypeName:'空管报警'},
        // { PTypeValue:'handleVoltmetre',PTypeName:'通讯板电压异常'},
        // { PTypeValue:'handleDays',PTypeName:'日用量预警'},
        // { PTypeValue:'handleMagnet',PTypeName:'强磁报警'},
        // { PTypeValue:'handleInstant',PTypeName:'瞬时流量数值突变'}
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantId: [
          {required: true, message: "归属水司不能为空", trigger: "change"}
        ],
        targetType: [
          {required: true, message: "报警对象类型不能为空", trigger: "change"}
        ],
        targetId: [
          {required: true, message: "报警对象不能为空", trigger: "blur"}
        ],
        targetName: [
          {required: true, message: "报警对象名称不能为空", trigger: "blur"}
        ],
        warnStatus: [
          {required: true, message: "报警状态", trigger: "change"}
        ],
        handleStatus: [
          {required: true, message: "处理状态", trigger: "change"}
        ],
        warnParamType: [
          {required: true, message: "报警参数", trigger: "change"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
      },
      filterText: '',
      // 报警类型
      alarmTypeList: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 315
    },
  },
  // mounted() {
  //   this.getAlarmType()
  // },
  methods: {
    updateLocationNb(locationNb){
      this.queryParams.locationNb = locationNb
      this.queryParams.targetId = locationNb
    },
    // 获取报警类型
    getAlarmType(){
      let tabList = []
      this.AlarmType = [{PTypeValue: '', PTypeName: '全部类型'}]
      getDicts('warn_param_type').then(res => {
        if(res.code === 200) {
          this.alarmTypeList = res.data
          this.alarmTypeList.forEach(item => {
            if(item.remark.substr(0, 4) === 'ELEC'){
              let obj = {
                PTypeValue: item.dictValue,
                PTypeName: item.dictLabel
              }
              tabList.push(obj)
            }
          })
          this.AlarmType.push(...tabList)
        }
      })
    },
    handleClick(tab) {
      if(tab._props.name === ''){
        this.queryParams.warnParamType = ''
      }
      this.queryParams.warnParamType = tab._props.name
      this.handleQuery()
      // if (tab._props.name === 'handleAll') {
      //   this.queryParams.warnParamType = ''
      //   this.handleQuery()
      // } else if (tab._props.name === 'zeroUsage') {
      //   this.queryParams.warnParamType = 4
      //   this.handleQuery()
      // } else if (tab._props.name === 'missUpload') {
      //   this.queryParams.warnParamType = 5
      //   this.handleQuery()
      // } else if (tab._props.name === 'flowIncrease') {
      //   this.queryParams.warnParamType = 6
      //   this.handleQuery()
      // }
    },
    /** 查询告警列表 */
    getList() {
      this.loading = true;
      if (this.recentlyWarnTime.length > 0) {
        this.queryParams.beginStartTime = this.recentlyWarnTime[0]
        this.queryParams.endStartTime = this.recentlyWarnTime[1]
      }
      listxbWarn(this.queryParams).then(response => {
        this.warnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        targetType: null,
        targetId: null,
        targetName: null,
        warnStatus: null,
        handleStatus: null,
        warnParamType: null,
        warnType: null,
        startTime: null,
        beginStartTime: null,
        endStartTime: null,
        Value: null,
        confirmedBy: null,
        recentlyWarnTime: null,
        freezeTime: null,
        warnValue: null,
        referenceValue: null,
        value: null,
        pd: null,
        terminalType: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.recentlyWarnTime = [moment().subtract(6, 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加告警";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWarn(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改告警";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWarn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWarn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      this.$modal.confirm('是否确认删除告警编号为"' + IDs + '"的数据项？').then(function () {
        return delWarn(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('alarmmanagement/warn/export', {
        ...this.queryParams
      }, `warn_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
<style lang="scss" scoped>
.form_col {
  width: 90%;
  ::v-deep .el-form {
    width: 100%;
  }
  ::v-deep .el-form-item {
    width: 25%;
  }
}

.form_query {
  width: 10%;
  text-align: right;
}
</style>
